package com.lvmama.service.dw.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.JedisCluster;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lvmama.common.constants.Constants;
import com.lvmama.common.result.CodeMessage;
import com.lvmama.common.result.Result;
import com.lvmama.common.utils.EncodeUtil;
import com.lvmama.common.utils.JSONConversionUtil;
import com.lvmama.common.utils.PageInfoUtil;
import com.lvmama.dao.dw.priceStock.StockDao;
import com.lvmama.pojo.dto.dw.StockDetailQuery;
import com.lvmama.pojo.entity.dw.priceStock.StockDetail;
import com.lvmama.service.dw.StockService;

/**
 * @Author:xuzhongwei
 * @Description:
 * @Date：2018/08/06
 */
@Slf4j
@Service("stockService")
public class StockServiceImpl implements StockService {

    @Autowired
    private StockDao stockDao;

    @Autowired
    private JedisCluster jedisCluster;

    @Override
    public Result<List<StockDetail>> selectStockDetail(StockDetailQuery query) {
    	
        log.info("selectStockDetail start, query:" + query);
        try {
            return Result.success(stockDao.selectStockDetail(query));
        } catch (Exception e) {
            log.error("selectStockDetail error:" + e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
    }

    @Override
    public Result<List<StockDetail>> selectStockDetailRedis(StockDetailQuery query) {
    	
    	try {
    		log.info("selectStockDetail start, query:" + query);
            String key = EncodeUtil.encodePassword(query.toString());
            if (!jedisCluster.exists(key)){
                List<StockDetail> list = stockDao.selectStockDetail(query);
                jedisCluster.set(key, JSONConversionUtil.objToString(list));
                jedisCluster.expire(key,Constants.TIMEOUT);
            }
            String result = jedisCluster.get(key);
            return Result.success(JSONConversionUtil.stringToList(result,StockDetail.class));
		} catch (Exception e) {
			 log.error("selectStockDetailRedis error:" + e.getMessage(), e);
			 return Result.error(CodeMessage.SERVER_ERROR);
		}
        
    }

    @Override
    public Result<PageInfo<StockDetail>> selectStockDetailPage(StockDetailQuery query) {
    	
        log.info("selectStockDetailPage start, query:" + ToStringBuilder.reflectionToString(query, ToStringStyle.DEFAULT_STYLE));
        //设置分页
        PageHelper.startPage(query.getCurrentPage(), query.getPageSize());
        try {
        	List<StockDetail> stockDetails = stockDao.selectStockDetail(query);
            return Result.success(new PageInfo<>(stockDetails));
        } catch (Exception e) {
            log.error("selectStockDetailPage error:" + e.getMessage(), e);
            return Result.error(CodeMessage.SERVER_ERROR);
        }
    }

    @Override
    public Result<PageInfoUtil<StockDetail>> selectStockDetailPageByRedis(StockDetailQuery query){
    	
        log.info("selectStockDetailPageByRedis start, query:" + ToStringBuilder.reflectionToString(query, ToStringStyle.DEFAULT_STYLE));
        
        try {
        	String key = EncodeUtil.encodePassword(query.toString());
            long total = jedisCluster.zcard(key);
            if (query.getCurrentPage() == 0){
            	query.setCurrentPage(1);
            }
            int pageStart = (query.getCurrentPage() - 1) * query.getPageSize();
            int pageEnd = pageStart + query.getPageSize() - 1;
            //如果total 小于0 表示没有缓存重新加载
            if (total <= 0){
                List<StockDetail>  stockDetails = stockDao.selectStockDetail(query);
                Map<String, Double> redisMap = new HashMap<>();
                if (stockDetails != null && stockDetails.size() > 0){
                    double i = 0D;
                    for (StockDetail stockDetail : stockDetails){
                        if (stockDetail == null){
                            continue;
                        }
                        String result = JSONConversionUtil.objToString(stockDetail);
                        redisMap.put(result,i);
                        i ++;
                    }
                }
                total = redisMap.size();
                jedisCluster.zadd(key, redisMap);
                jedisCluster.expire(key,Constants.TIMEOUT);

            }
            Set<String> resultSet = jedisCluster.zrange(key, pageStart, pageEnd);
            List<StockDetail> list =  new ArrayList<>();

            if (resultSet != null && resultSet.size() > 0){
                for (String detail : resultSet){
                    StockDetail stockDetail = JSONConversionUtil.stringToObj(detail,StockDetail.class);
                    if (stockDetail != null){
                        list.add(stockDetail);
                    }
                }
            }
            return Result.success(new PageInfoUtil<StockDetail>(list, query.getCurrentPage(), query.getPageSize(), total, pageStart, pageEnd));
		} catch (Exception e) {
			log.error("selectStockDetailRedis error:" + e.getMessage(), e);
			return Result.error(CodeMessage.SERVER_ERROR);
		}
        
    }
}
